/**
 * Created by vincent on 16-4-22.
 */
'use strict';

/* App Module */

var marketApp = angular.module('publicMarketApp', ['ngRoute', 'ngResource', 'marketFilters']);
var params = {};
var tempArray = window.location.search.split('?');
if (tempArray.length == 2) {
    var parts = tempArray[1].split('&');
    for (var i = 0; i < parts.length; i++) {
        var nv = parts[i].split('=');
        if (!nv[0]) continue;
        params[nv[0]] = nv[1] || true;
    }
}
//var host = 'localhost:3000';
/*var host = 't.app.66xiaoqu.com';*/
/*  宝宝树66小区二次改造    mod   dayu.wedo  20170723   start   */
var host = 'app-66xiaoqu.babytree.com';
//var host = 'app.h2oprint.com';
/*  宝宝树66小区二次改造    mod   dayu.wedo  20170723   end   */
//var host = "192.168.1.26:3000";

marketApp.controller('GoodsListCtrl', ['$scope', 'GoodList', 'Banner',
    function ($scope, GoodList, Banner) {

        ///* =================================== SALE STUFF =================================== */
        //var startTime = moment().startOf('week').add(6, 'day').add(18, 'hour');
        //var endTime = moment().startOf('week').add(6, 'day').add(22, 'hour');
        //$showSale();
        //function $showSale() {
        //    if (moment().isBetween(startTime, endTime)) {
        //        if (localStorage.getItem('saleFlag') == null) {
        //            $('#sale_url').attr('href', "http://" + host + "/market/recommend.html" + window.location.search);
        //            $disableScroll();
        //            $('#sale').css('display', 'block');
        //        }
        //    } else {
        //        localStorage.removeItem('saleFlag');
        //    }
        //}
        //
        //var time = startTime.toDate().getTime() - new Date().getTime();
        //setTimeout($showSale, time);
        //
        //$scope.gotoSale = function () {
        //    localStorage.setItem('saleFlag', 1);
        //    $('#sale').css('display', 'none');
        //    $enableScroll();
        //};
        //$scope.hideSale = function () {
        //    document.getElementById('reged').style.display = 'none';
        //};

        /* =================================== BANNER STUFF =================================== */
        $scope.bannerList = Banner.getBanner(function (result) {
            var lenn = result.data.length;

            var str = "";
            for (var i = 0; i < result.data.length; i++) {
                //var url = "";
                //if (result.data[i].url.indexOf('?') > 0) {
                //    url = result.data[i].url + "&token=" + params.token + "&deviceId=" + params.deviceId + '&clickSource=701';
                //} else {
                //    url = result.data[i].url + "?token=" + params.token + "&deviceId=" + params.deviceId + '&clickSource=701';
                //}
                //str += '<div class="swiper-slide"><a href="' + url + '"><img src="' + result.data[i].imageURL + '"></a></div>';
                str += '<div class="swiper-slide"><img src="' + result.data[i].imageURL + '"></a></div>';
            }
            $('.swiper-wrapper').html(str);

            var swiperClass = '.swiper-container';

            var swiperBanner = new Swiper(swiperClass, {
                pagination: '.pagination',
                paginationClickable: true,
                loop: true
            });

            if (lenn > 0) {
                $(swiperClass).css('padding', '3px 0 5px 0');
                $(swiperClass).css('background-color', '#eeebeb');
            } else {
                $(swiperClass).css('visibility', 'hidden');
            }

            if (lenn > 1) {
                setInterval(function () {
                    swiperBanner.swipeNext();
                }, 4000);
            }

            //$('.swiper-slide').click(function () {
            //    ClickLog.save({}, {type: 40, typeDesc: '集市banner', 'userId': params.token})
            //});

            $('.loading-pop').hide();

        }, function (err) {
            $('#load_img').hide();
            $('#reload').show()
        });

        /* =================================== 页面 =================================== */

        var no_goodsText = "空空的，赶紧按下面“+”号发布闲置吧～"
        var no_servicesText = "服务版块近期即将开放，敬请期待！"
        var no_localText = "空空的，赶紧按下面“+”号发布内容吧～"

        $scope.no_goodsText = "";


        $scope.goodsImgW = ($(window).width()) * 0.3 + 'px';
        $scope.goodsImgH = ($(window).width()) * 0.3 + 'px';

        $scope.rangeList = [
            {name: '同城', value: 'city', img: 'images/range_city.png'},
            //{name: '周边小区', value: 'around'},
            {name: '本小区', value: 'only', img: 'images/range_only.png'}
        ];

        /* 获数据的parameters  */
        $scope.goodsList = [];   // data
        $scope.ts = 0;          // page number
        $scope.type = 0;        // 1:非免费，2:免费
        $scope.itemType = 1;   // 0: 全部, 1:闲置，2:服务  // default: goods
        $scope.range = $scope.rangeList[0].value; // default: city

        /* 逻辑 */

        var sessionItemType = sessionStorage.getItem("itemType");
        var sessionColumn = sessionStorage.getItem("column");

        $scope.clickGoods = function () {
            $linkActive(1);
            $scope.itemType = 1;
            $scope.ts = 0;
            $scope.range = $scope.rangeList[0].value;
            sessionStorage.setItem('column', "goods");
            getNewData(true);
        };

        $scope.clickServices = function () {
            $linkActive(2);
            $scope.itemType = 2;
            $scope.ts = 0;
            $scope.range = $scope.rangeList[0].value;
            sessionStorage.setItem('column', "services");
            getNewData(true);
        };

        if (params.itemType && params.itemType != sessionItemType) {
            $scope.itemType = parseInt(params.itemType);
            if ($scope.itemType == 2) {
                $scope.clickServices();
            } else {
                $scope.clickGoods();
            }
            sessionStorage.setItem('itemType', $scope.itemType);
        } else {
            if (sessionColumn == "services") {
                $scope.clickServices();
            } else {
                $scope.clickGoods();
            }
        }

        $(".wrapper").on("swipeleft", swipeLeftHandler);
        $(".wrapper").on("swiperight", swipeRightHandler);

        function swipeLeftHandler(event) {
            if ($scope.itemType == 1) {
                $scope.clickServices();
            }
        }

        function swipeRightHandler(event) {
            if ($scope.itemType == 2) {
                $scope.clickGoods();
            }
        }

        var isMore = true;//判断是否有更多数据
        var isfinish = true;//isfinish判断每次数据是否加载完成，完成了才可进行下一次加载
        var isFlag = false;

        //获取数据hv
        function getNewData(flag) {
            if (flag)
                $('.loading-pop').show();
            GoodList.get({
                ts: $scope.ts,
                type: $scope.type,
                itemType: $scope.itemType,
                range: $scope.range
                //category: $scope.itemType == 1 ? $scope.category : $scope.servicesCategory,
                //sort: $scope.sort
            }, function (result) {
                $scope.ts = result.data.ts;

                //console.log("TS", $scope.ts)
                if (flag) {
                    $scope.goodsList = result.data.list;
                } else {
                    $scope.goodsList = $scope.goodsList.concat(result.data.list);
                }

                $nogoodsDisplay($scope.goodsList.length == 0);
                if ($scope.itemType == 2) {
                    $scope.no_goodsText = no_servicesText;
                } else if ($scope.itemType == 0) {
                    $scope.no_goodsText = no_localText;
                } else {
                    $scope.no_goodsText = no_goodsText;
                }

                isfinish = true;
                isMore = true;
                if (result.data.list.length == 0) {
                    isMore = false;
                }
                $('.loading-pop').hide();
                $(".loadingMore").html('');
            });
        }

        var count = 0;
        //2、滚动加载更多
        $('.wrapper').scroll(function () {
            if (params.type == 'ios') {
                $iosScrollTop();
            }

            var show = count == 0 ? 1 : $('.categorylist-w').offset().top;

            count++;
            var firstLoad = show > 0;
            //$categoryVisibility(firstLoad);
            if (!isMore){
                var contentHeight = $(".wrapper")[0].scrollHeight;
                var h = $(".wrapper").height();
                if ((contentHeight - h - $(this).scrollTop()) <= 10) {
                    $loadingDonePopup();
                }
            }
            else if (isMore && isfinish) {
                var contentHeight = $(".wrapper")[0].scrollHeight;
                var h = $(".wrapper").height();
                if ((contentHeight - h - $(this).scrollTop()) <= 75) {
                    isfinish = false;
                    $(".loadingMore").html('<img src="images/loading.gif" />正在加载');
                    //此处为加载下一条的方法
                    if (!firstLoad)
                        getNewData(false);
                    else
                        $scrollTop();
                }
            }
        }).scroll();

        $scope.reload = function () {
            document.location.reload()
        };

        //去二手详情
        $scope.goToDetail = function (goods) {

            //if ((!moment().isBetween(startTime, endTime)) && goods.saleNumber != null) {
            //    $('#saleRecordMsg').text(goods.isRecord ? '已标注' : '到时通知我');
            //    $('#reged').css('display', 'block');
            //    $scope.goods = goods;
            //} else {
                window.location.href = "detail_public.html" + '?goodsId=' + goods.objId + '&createdBy=' + goods.createdBy + '&clickSource=702';
            //}
        };


    }
]);


marketApp.factory('Banner', ['$resource', function ($resource) {
    return $resource('http://' + host + '/rest/v1.0/public/market/banners', {},
        {
            getBanner: {
                method: 'GET',
                timeout: 10000
            }
        }
    )
}]);

marketApp.factory('GoodList', ['$resource', function ($resource) {
    return $resource('http://' + host + '/rest/v1.0/public/market/goods/list/:ts', {});
}]);
